package com.example.tech.folio.controller;

import com.example.tech.folio.mapper.AdminMapper;
import com.example.tech.folio.pojo.entity.Admin;
import com.example.tech.folio.pojo.param.AdminLoginParam;
import com.example.tech.folio.pojo.param.AdminUpdatePasswordParam;
import com.example.tech.folio.pojo.vo.AdminLoginResultVO;
import com.example.tech.folio.web.JsonResult;
import com.example.tech.folio.web.State;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    @Autowired
    private AdminMapper adminMapper;

    // 处理登录请求的方法
    @PostMapping("/login")
    public JsonResult login(AdminLoginParam param, HttpSession session) {
        // 检查登录
        Admin admin = adminMapper.selectByUsername(param.getUsername());
        if (admin == null) {
            throw new RuntimeException(State.ERR_UNAUTHORIZED_USERNAME);
        }
        if (!admin.getPassword().equals(param.getPassword())) {
            throw new RuntimeException(State.ERR_UNAUTHORIZED_PASSWORD);
        }

        // 创建登录结果对象
        AdminLoginResultVO loginResult = new AdminLoginResultVO();
        loginResult.setId(admin.getId());
        loginResult.setUsername(admin.getUsername());

        // 将登录结果保存到Session中
        session.setAttribute("admin", loginResult);
        return JsonResult.ok(loginResult);
    }

    @PostMapping("/password/update")
    public JsonResult updatePassword(AdminUpdatePasswordParam param, HttpSession session) {
        // 从Session中获取登录结果
        AdminLoginResultVO loginResult = (AdminLoginResultVO) session.getAttribute("admin");
        Long adminId = loginResult.getId();

        // 检查旧密码
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new RuntimeException(State.ERR_NOT_FOUND);
        }
        if (!admin.getPassword().equals(param.getOldPassword())) {
            throw new RuntimeException(State.ERR_UNAUTHORIZED_PASSWORD);
        }

        // 修改密码
        Admin updateAdmin = new Admin();
        updateAdmin.setId(adminId);
        updateAdmin.setPassword(param.getNewPassword());
        adminMapper.updateById(updateAdmin);
        return JsonResult.ok();
    }

    // 处理登出请求的方法
    @PostMapping("/logout")
    public JsonResult logout(HttpSession session) {
        session.invalidate();
        return JsonResult.ok();
    }

}